#!/bin/bash

# 定义项目的根目录，当前目录作为默认值
PROJECT_DIR=$(pwd)
# 获取项目目录名
PROJECT_NAME=$(basename "$PROJECT_DIR")
# 定义构建目录
BUILD_DIR="$PROJECT_DIR/build"

# 检查是否传入了参数
if [ $# -gt 0 ]; then
    if [ "$1" = "clean" ]; then
        # 如果参数为 clean，则删除构建目录
        if [ -d "$BUILD_DIR" ]; then
            rm -rf "$BUILD_DIR"
            echo "The build directory has been cleaned."
        else
            echo "The build directory does not exist, no need to clean."
        fi

        # 删除根目录下与项目目录同名的 .elf 文件
        ELF_FILE="$PROJECT_DIR/$PROJECT_NAME.elf"
        if [ -f "$ELF_FILE" ]; then
            rm "$ELF_FILE"
            echo "The $ELF_FILE file has been deleted."
        else
            echo "The $ELF_FILE file was not found, no need to delete."
        fi
        exit 0
    fi
fi

# 检查构建目录是否存在，如果不存在则创建
if [ ! -d "$BUILD_DIR" ]; then
    mkdir -p "$BUILD_DIR"
fi

# 进入构建目录
cd "$BUILD_DIR"

# 运行 CMake 生成 Makefile
cmake ..

# 检查 CMake 是否成功运行
if [ $? -eq 0 ]; then
    # 运行 make 进行编译
    make
else
    echo "CMake failed to run. Please check the project's CMakeLists.txt file."
fi    